<?php

        /**
         * 用户操作类
         */

        class UserController{

                private $db;
                public function __construct(){
                        $this->db = include "./Data/data.php";
                }

                public function Login(){
                        if(!empty($_POST)){
                                foreach ($this->db as $user) {
                                        //用户名和密码都符合
                                        if($user['username'] == $_POST['username'] && $user['password'] == md5($_POST['password'])){
                                                //把什么存入session?
                                                $_SESSION['username'] = $_POST['username'];
                                                msg('登陆成功', './index.php');
                                        }
                                }
                                msg('用户名或者密码错误', 'index.php');
                        }
                        $this->display('Login');
                }

                public function Regsiter(){
                        if(!empty($_POST)){
                                //1.先判断用户名是否已存在
                                foreach ($this->db as $user) {
                                        //用户名和密码都符合
                                        if($user['username'] == $_POST['username']){
                                                msg('用户名不能重复', './index.php');
                                        }else{
                                                //2.添加数据
                                                $this->db[] = array(
                                                    'username' => $_POST['username'],
                                                    'email' => $_POST['email'],
                                                    'password' => md5($_POST['password'])
                                                );
                                                $phpCode = "<?php return " . var_export($this->db,true) . "?>";
                                                file_put_contents('./Data/data.php', $phpCode);
                                                msg('注册成功', './index.php');
                                        }
                                }
                        }
                }

                public function Logout(){
                        unset($_SESSION['username']);
                        session_destroy();
                        msg('退出成功', './index.php');
                }
                //加载模板方法
                protected function display($tpl){
                        include "./Templates/{$tpl}.html";
                }
        }
?>